import 'package:e_reception_flutter/common_widgets/common_search_bar_widget/common_search_bar_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_sliver_delegate/common_sliver_delegate.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/company/company_add_user_edit_info/bean/company_add_user_edit_info_type.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/department_or_class_list_response.dart';
import 'package:e_reception_flutter/ui/company/company_detail/class_or_department/class_or_department_page.dart';
import 'package:e_reception_flutter/ui/company/company_detail/class_or_department/class_or_department_viewmodel.dart';
import 'package:e_reception_flutter/ui/company/unactive_person/unactive_list_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_add_admin_edit/binding_add_admin_edit_page.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/vg_widgets/annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/mixin/vg_place_holder_status_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';

import '../common_person_list_item_widget.dart';
import '../common_person_list_response.dart';
import '../company_person_list_view_model.dart';
import 'add_manager_page.dart';

///企业主页 管理员列表 添加选择
class SelectUserPage extends StatefulWidget {
  static const String ROUTER = 'SelectUserPage';

  ///班级或部门信息
  final DepartmentOrClassListItemBean oldBean;

  ///需要过滤的id
  final List<String> filterIds;

  const SelectUserPage({Key key, this.oldBean, this.filterIds})
      : super(key: key);

  ///跳转方法
  ///
  /// filterIds 需要过滤的用户id
  static Future<bool> navigatorPush(BuildContext context,
      {List<String> filterIds, DepartmentOrClassListItemBean oldBean}) {
    return RouterUtils.routeForFutureResult<bool>(
      context,
      SelectUserPage(
        oldBean: oldBean,
        filterIds: filterIds,
      ),
      routeName: SelectUserPage.ROUTER,
    );
  }

  @override
  State<StatefulWidget> createState() {
    return SelectUserPageState();
  }
}

class SelectUserPageState
    extends BasePagerState<CommonPersonBean, SelectUserPage>
    with VgPlaceHolderStatusMixin<CommonPersonBean, SelectUserPage> {
  CommonPersonListViewModel _viewModel;

  @override
  void initState() {
    super.initState();
    String pageType;
    if(widget.oldBean != null){
      if (widget.oldBean.isClass()) {
        pageType="01";
      }else{
        pageType='00';
      }
    }
    _viewModel = CommonPersonListViewModel(
        this,
        widget.oldBean != null
            ? CommonPersonListViewModel.TYPE_SELECT_MEMBER
            : CommonPersonListViewModel.TYPE_SELECT_MEMBER_NO_ADMIN,
        id: widget.oldBean?.getId(),pageType: pageType);
    _viewModel.refresh();
  }

  @override
  Widget build(BuildContext context) {
    return CustomAnnotatedRegion(
      Scaffold(
        backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
        body: Column(
          children: <Widget>[
            _toTopBarWidget(),
            Expanded(
              child: NestedScrollView(
                headerSliverBuilder: (context, bool) {
                  return [
                    SliverPersistentHeader(
                      delegate: CommonSliverPersistentHeaderDelegate(
                          child: Container(
                            color: ThemeRepository.getInstance()
                                .getCardBgColor_21263C(),
                            padding: EdgeInsets.symmetric(vertical: 10),
                            child: CommonSearchBarWidget(
                              autoFocus: true,
                              hintText: "搜索",
                              onChanged: (keyword) {
                                _viewModel.keyword = keyword;
                                _viewModel.refresh();
                              },
                              onSubmitted: (keyword) {
                                _viewModel.keyword = keyword;
                                _viewModel.refresh();
                              },
                            ),
                          ),
                          maxHeight: 50,
                          minHeight: 50),
                    )
                  ];
                },
                body: _toPullRefreshWidget(),
              ),
            )
          ],
        ),
      ),
      navigationBarColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
    );
  }

  ///topbar
  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      title: "请选择",
      titleFontSize: 17,
      isShowBack: true,
    );
  }

  Widget _toPullRefreshWidget() {
    return MixinPlaceHolderStatusWidget(
        errorOnClick: () => _viewModel.refresh(),
        // emptyOnClick: () => _viewModel.refresh(),
        child: Container(
          color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
          child: VgPullRefreshWidget.bind(
              state: this,
              viewModel: _viewModel,
              enablePullDown: false,
              child: ListView.separated(
                  itemCount: data?.length ?? 0,
                  padding: const EdgeInsets.all(0),
                  physics: BouncingScrollPhysics(),
                  keyboardDismissBehavior:
                      ScrollViewKeyboardDismissBehavior.onDrag,
                  itemBuilder: (BuildContext context, int index) {
                    if (data == null ||
                        data.length <= index ||
                        (widget.filterIds != null &&
                            widget.filterIds.contains(data[index].fuid))) {
                      return Container();
                    }
                    return _listItem(index);
                  },
                  separatorBuilder: (BuildContext context, int index) {
                    return SizedBox(
                      height: 0,
                    );
                  })),
        ));
  }

  @override
  void finishRefresh({Duration duration}) {
    super.finishRefresh(duration: duration);
    loading(false);
  }

  @override
  void finishLoadMore() {
    super.finishLoadMore();
    loading(false);
  }

  /// 列表项
  Widget _listItem(int index) {
    CommonPersonBean item = data[index];

    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () async {
        bool result;
        if (widget.oldBean != null) {
          if (CompanyAddUserEditInfoIdentityExtension.getIdToTypeStr(
                  item.roleid) !=
              CompanyAddUserEditInfoIdentityType
                  .commonUser){
            //管理员就直接添加
              _viewModel.addAdmin(context, widget.oldBean.getId(), item.userid);
          } else{
            if (widget.oldBean.isClass()) {
              result = await AddManagerFromSelectPage.navigatorPush(
                  context, item.fuid,
                  classid: widget.oldBean?.getId(), className: widget.oldBean?.getName());
            }
            if (widget.oldBean.isDepartment()) {
              result = await AddManagerFromSelectPage.navigatorPush(
                  context, item.fuid,
                  departmentId: widget.oldBean?.getId(),
                  department: widget.oldBean?.getName());
            }
          }
        } else {
          result =
              await AddManagerFromSelectPage.navigatorPush(context, item.fuid);
        }
        if (result != null && result) {
          data.removeAt(index);
          setState(() {});
          RouterUtils.pop(context, result: true);
        }
      },
      child: Container(
        height: 60,
        child: CommonListItemWidget(
          putpicurl: item.putpicurl,
          napicurl: item.napicurl,
          name: item.name,
          nick: item.nick,
          phone: item.phone,
          department: item.department,
          projectname: item.projectname,
          city: item.city,
          isAlive: item.isAlive(),
          groupName: item.groupName,
          number: item.number,
          uname: item.uname,
          lastPunchTime: item.lastPunchTime,
          roleid: item.roleid,

        ),
        color: ThemeRepository.getInstance().getCardBgColor_21263C(),
        padding: EdgeInsets.symmetric(vertical: 12, horizontal: 15),
      ),
    );
  }
}
